package com.llk.algorithm;

/**
 * 最长公共前缀
 *
 * @description: 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀，返回空字符串 ""。
 * @author: liulukuan
 * @since: 2020/10/31 18:08
 */
public class LongestCommonPrefix {

    /**
     * 输入: ["flower","flow","flight"]
     * 输出: "fl"
     * <p>
     * 输入: ["dog","racecar","car"]
     * 输出: ""
     * 解释: 输入不存在公共前缀。
     */
    public static void main(String[] args) {
        String[] strs = new String[]{""};
        System.out.println(longestCommonPrefix(strs));
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        if (strs.length == 1) {
            return strs[0];
        }
        String prefix = strs[0];
        for (int i = 1; i < strs.length; i++) {
            prefix = getPrefix(prefix, strs[i]);
            if (prefix.length() == 0) {
                return "";
            }
        }
        return prefix;
    }

    public static String getPrefix(String prefix, String str) {
        if (prefix == null || str == null) {
            return "";
        }
        int strLenth = Math.min(prefix.length(), str.length());

        int i = 0;
        while (i < strLenth && prefix.charAt(i) == str.charAt(i)) {
            i++;
        }
        return prefix.substring(0, i);
    }
}
